/*********************************************************************************
 * 
 *       Filename:  pub.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(26/09/21)
 *         Author:  lastbreath <2631336290@qq.com>
 *      ChangeLog:  1, Release initial version on "26/09/21 12:46:58"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include "mosquitto.h"
#include "mqtt_client.h"

#include <errno.h>

#define HOST "localhost"
#define PORT 1883
#define KEEP_ALIVE 60
#define MSG_MAX_SIZE 512


static int running = 1;
static struct mosquitto *mosq = NULL;

static void my_connect_callback(struct mosquitto *mosq,void *obj,int rc)
{
    printf("Call the function: my_connect_callback.\n");
}

static void my_disconnect_callback(struct mosquitto *mosq,void *obj,int rc)
{
    
    printf("Call the function: my_disconnect_callback.\n");
    running = 0;
}

static void my_publish_callback(struct mosquitto *mosq,void *obj,int mid)
{
    printf("Call the function: my_publish_callback.\n");

}

unsigned short client_publish_init_connect(const char* host, 
            const char* port, 
            const char* username, const char* password)
{
    int rv;

    mosquitto_lib_init();

    mosq = mosquitto_new(NULL, true, NULL);
    if(mosq == NULL)
    {
        printf("New pub_test error: %s\n",strerror(errno));
        mosquitto_lib_cleanup();
    }

    mosquitto_username_pw_set(mosq, username, password);
    mosquitto_connect_callback_set(mosq, my_connect_callback);
    mosquitto_disconnect_callback_set(mosq, my_disconnect_callback);
    mosquitto_publish_callback_set(mosq, my_publish_callback);

    rv = mosquitto_connect(mosq, host, atoi(port), KEEP_ALIVE);

    if(rv)
    {
        printf("Connect server error: %s\n",strerror(errno));
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return 1;
    }
    return 0;

}

unsigned short mqtt_client_publish(const char* topic, const char* message)
{
    int loop = mosquitto_loop_start(mosq);
    if(loop)
    {

        printf("mosquitto loop error: %s\n",strerror(errno));
        mosquitto_destroy(mosq);
    	mosquitto_lib_cleanup();
        return 1;
    }

    int ret = mosquitto_publish(mosq, NULL, topic, strlen(message), message, 0, 0);

    if (ret != MOSQ_ERR_SUCCESS)
        return 1;
    
    else return 0;
}


void client_publish_release_resource()
{
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();

    printf("mqtt client release publish resource!\n");
}

// int main (int argc, char **argv)
// {

//     if (mqtt_client_connect()) 
//     {
//         printf("mqtt client connect failed");
//     }

//     char* topic = "mqtt/test";
//     char* message = "hello mqtt";

//     mqtt_client_publish(topic, message);


//     return 0;
// }
